<template>
  <div class="box">
    请输入内容：{{ baseUrl }}
    <!-- 开启div可编辑模式-->
    <div ref="editor" :contenteditable="contenteditable" class="editor-box" @input="input">
      <!-- <el-input type="textarea" v-model="form.desc"></el-input> -->
    </div>
    <el-button type="primary" @click="submit">提交</el-button>
    <el-button type="primary" @click="clear($event)" plain>清空</el-button>
  </div>
</template>

<script>
export default {
  name: 'ClipBoardView',

  data() {
    return {
      contenteditable: true,
      baseUrl: ''
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    input() {
      this.$refs.editor.innerHTML = ''
    },
    init() {
      const editor = this.$refs.editor
      editor.addEventListener('paste', (e) => {
        console.log(e)
        if (e.clipboardData.files[0]) {
          e.preventDefault()
          const file = e.clipboardData.files[0]; // 获取文件对象
          const reader = new FileReader(); // 创建FileReader对象
          // 将文件读取为DataURL格式
          reader.readAsDataURL(file);
          // 当文件读取完成时，执行以下操作
          reader.onload = (event) => {
            // 创建一个img元素
            const img = document.createElement('img');
            // 将读取到的文件内容赋值给img的src属性
            img.src = event.target.result;
            // 将img元素添加到editor元素中
            this.baseUrl = event.target.result
            console.log(event.target.result,'event.target.result')
            this.contenteditable = false
            editor.appendChild(img)
          };
          
        }
      })
    },
    clear(){
      const editor = this.$refs.editor;
      editor.innerHTML = '';
      this.contenteditable = true
      this.baseUrl = ''
    },
    submit() {
      const html = this.$refs.editor.innerHTML
      const arr = html.split('<img src="')
      const imgArr = arr.filter(item => item.includes('data:image'))
      const htmlArr = []
      console.log('arr',arr)
      arr.forEach((item) => {
        if(item.includes('">')){
          console.log('includes',item)
          htmlArr.push(item.split('">')[0])
          htmlArr.push(item.split('">')[1])
        }else {
          htmlArr.push(item)
        }
      });
      console.log(htmlArr,imgArr)
    },
  }
}
</script>
<style lang="scss" scoped>
.box {
  width: 500px;
  margin: 0 auto;
  padding: 20px;
  text-align: left;

  .editor-box {
    border: 1px solid #ddd;
    min-height: 40px;
    border-radius: 5px;

    &:focus-visible {
      border: 1px solid #f00;
      outline: none;
    }
  }
}
</style>
